<?php
declare(strict_types=1);

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\Code\Normal;
use App\Model\PssLogModel\ManagerLog;
class Manager extends BasePssModel
{
    public $table           = 'manager';
    public $loginToken      = 'mbpps_loginToken__';
    public $loginVolidTime  = 3600 * 24;
    public $rdb             = 1;
    public $node            = "ych5work_0_1";
    /**
     * 云仓移动端登录
     * @author chenyun
     */
    public function login(array $param = [])
    {
        if (empty($param['account'])) {
            return Normal::returnCode(Normal::FAIL,'账号不能为空');
        }
        
        if (empty($param['password'])) {
            return Normal::returnCode(Normal::FAIL,'密码不能为空');
        }
        
        $manager = Manager::instance()->info(['account' => $param['account']]);
        if (empty($manager)) {
            return Normal::returnCode(Normal::FAIL,'账号不存在，或者密码错误');
        }
        
        if ($manager["status"] != 1 ) {
            return Normal::returnCode(Normal::FAIL,'该用户被禁用，请联系管理员');
        }
        
        //超级管理员用户验证权限组
        if( !in_array($manager['account'], ['root']) ) {
            $role = Role::instance()->info(['id' => $manager['role_id']]);
            if ($role['status'] != 1) {
                return Normal::returnCode(Normal::FAIL,'权限组被禁用，请联系管理员');
            }
            if(strstr($role["node"],$this->node) == false){
                return Normal::returnCode(Normal::FAIL,'没有该系统权限，请联系管理员');
            }
        }
        //校验密码是否正常
        $str = $this->getUserSecretPassWord($param['password']);
        $password = md5($str);
        $hasPassword = md5($manager['password']);
        if( $hasPassword != $password ) {
            return Normal::returnCode(Normal::FAIL,'登录密码错误');
        }
        
        if(!extension_loaded('redis')) {
            return Normal::returnCode(Normal::FAIL,'登录失败，缺少扩展');
        }
        $token = $this->getToken($manager);
        
        redis()->set(
            $this->loginToken.'_'.$token,
            $manager['id'],
            $this->loginVolidTime
        );
        $data = [
            'manager_id'    => $manager['id'],
            'manager_name'  => $manager['name'],
            'content'       => '从移动端登录成功',
            'ip'            => getIp(),
            'url'           => request()->url(),
            'cd'            => time(),
        ];
        
        ManagerLog::instance()->add($data);
        return Normal::returnCode(Normal::SUC,'登录成功',[
            'token'     => $token,
            'account'   => $manager['account'],
        ]);
    }

    /**
     * 处理密码加密规则
     * @param string $password
     */
    public function getUserSecretPassWord( string $string )
    {
        return base64_encode(md5($string,true));
    }
    /**
     * 获取token
     * @param array $user
     */
    public function getToken( $user = [] )
    {
        $timestamp = time();
        $encrptstr = implode("_", [
            $user['id'],
            $user['password'],
            $timestamp
        ]);
        return md5(md5($encrptstr));
    }
    
    /**
     * @登录验证
     */
    public function checkLogin($param)
    {
        $token = $param["token"];
        if(empty($token)) {
            return Normal::returnCode(Normal::NO_LOGIN,'未登录');
        }
        if( !extension_loaded('redis') ) {
            return Normal::returnCode(Normal::FAIL,'redis class not found');
        }
        
        $redis= redis();
        $uid = $redis->get($this->loginToken.'_'.$token);
        //token是否有效
        if( empty($uid) ) {
            $this->clearCache($token);
            return Normal::returnCode(Normal::NO_LOGIN,'登录失效，请重新登录');
        }
        
        //查询账户是否处于被禁用状态
        $manage = $this->where('id',$uid)->first()->toArray();
        if(empty($manage)) {
            $this->clearCache($token);
            return Normal::returnCode(Normal::NO_LOGIN,'获取用户信息错误，请重新登录');
        }
        //查看角色组是否被禁用
        if( $manage['role_id'] ) {
            $roleInfo = Role::instance()->info([
                'id'  => $manage['role_id'],
                'df' => 0
            ]);
            if(empty($roleInfo)) {
                $this->clearCache($token);
                return Normal::returnCode(Normal::NO_LOGIN,'当前账户未设置权限角色组，请先设置');
            }
    
            if( $roleInfo['is_root'] != 1 && $roleInfo['status'] == 0 ) {
                $this->clearCache($token);
                return Normal::returnCode(Normal::NO_LOGIN,'当前账户对应权限角色组处于禁用状态，暂时不能使用当前系统');
            }
        }

        return Normal::returnCode(Normal::SUC,'校验成功',[
            'manager_id'    => $manage['id'],
            'manager_name'  => $manage['name'],
            'token'         => $token,
            'account'       => $manage['account'],
        ]);
    }
    /**
     * 清除缓存
     * @param string $token
     */
    public function clearCache( $token ) {
        $redis= redis();
        $redis->del($this->loginToken.$token);
        return Normal::returnCode(Normal::SUC,'操作成功');
    }
}